const $ = layui.jquery;
let table = layui.table;
let laydate = layui.laydate;
let form = layui.form;
$(() => {
    //渲染表格
    table.render({
        elem: '#adm-tbl',
        url: ctx + "/sys/api/v1/admin",//向后台提交数据的地址
        method: "get",//默认就是get
        toolbar: "#adm-toolbar",
        defaultToolbar: ['filter', 'exports', 'print'],//右边的按钮
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', title: 'ID', width: 80, sort: true, fixed: "left"},
            {
                field: 'avatarUrl', title: '头像', width: 60, fixed: "left",templet: function (row) {//row是当前行
                    if(row.avatarUrl!=null&&row.avatarUrl!==''){
                        let url = ctx + "/assets/"+row.avatarUrl;
                        return "<div class='avatar' style='background-image: url(" + url + ")'></div>"
                    }else{
                        return ""
                    }

                }
            },
            {field: 'username', title: '管理名', width: 120, fixed: "left"},
            {field: 'password', title: '密码', minWidth: 120},
            {field: 'phone', title: '电话', minWidth: 120},
            {field: 'locked', title: '锁定状态', width: 100,templet:function (row){
                if(row.locked){
                    return "是";
                }else{
                    return "否";
                }
                }},
            {field: 'userExpireTime', title: '账号过期时间', width: 160,templet:function (row){
                    if(row.userExpireTime){
                        return layui.util.toDateString(new Date(row.userExpireTime),'yyyy-MM-dd HH:mm:ss');
                    }else{
                        return null;
                    }
                }},
            {field: 'credExpireTime', title: '权限过期时间', width: 160,templet:function (row){
                    if(row.credExpireTime){
                        return layui.util.toDateString(new Date(row.credExpireTime),'yyyy-MM-dd HH:mm:ss');;
                    }else{
                        return null;
                    }
                }},
            {field: 'loginTimes', title: '登录次数', width: 100},
            {field: 'lastLoginTime', title: '上次登录时间', width: 160},
            {field: 'lastLoginIp', title: '上次登录地址', width: 160},
            {field: 'description', title: '备注', minWidth: 160},
            {field: 'createdTime', title: '创建时间', width: 160},
            {field: 'createdBy', title: '创建人', width: 100},
            {field: 'updatedTime', title: '修改时间', width: 160},
            {field: 'updatedBy', title: '修改人', width: 100},
            {fixed: 'right', title: '操作', toolbar: '#rowBar', width: 120}
        ]],
        page: true, // 是否显示分页
        limits: [5, 10, 20, 30],
        limit: 10 // 每页默认显示的数量
    });
    //渲染账号时间和登录时间的日期时间输入框
    laydate.render({
        elem: "[name=credExpireTimeRange]",
        range: "~",
        type:"datetime"
    });
    laydate.render({
        elem: "[name=lastLoginTimeRange]",
        range: "~",
        type:"datetime"
    });
    //添加事件，使用on,工具栏事件
    table.on("toolbar(adm-tbl)", function (obj) {
            if (obj.event === "reset") {
                //重置
                $("#adm-search-form")[0].reset();
            } else if (obj.event === "search") {
                reload();
                $("#adm-search-form")[0].reset();
            } else if (obj.event === "del") {//批量删除，安全删除
                let status = table.checkStatus("adm-tbl");
                let checked = status.data;//获取选中的数据
                let ids = [];
                checked.forEach(it => ids.push(it.id));
                if (ids.length === 0) {
                    layer.msg("请选中您要删除的行")
                } else {
                    layer.confirm("是否确认删除选中的行?", function (index) {
                        deleteByIds(ids);
                        reload();
                        layer.close(index);
                    });
                }
            } else if (obj.event === "add") {
                add();
            } else if (obj.event === "edit") {
                let status = table.checkStatus("adm-tbl");
                let checked = status.data;//获取选中的数据
                if (checked.length === 0) {
                    layer.msg("请选中您要修改的行")
                } else if (checked.length > 1) {
                    layer.msg("一次最多修改一行")
                } else {
                    let admin = checked[0];
                    edit(admin);
                }

            }
        }
    );

//     行工具栏
    table.on("tool(adm-tbl)", function (obj) {
        if (obj.event === "del") {
            let rowData = obj.data;//选中的行的数据
            layer.confirm("是否确认删除选中的行?", function (index) {
                deleteByIds([rowData.id]);
                reload();
                layer.close(index);
            });
        } else if (obj.event === "edit") {
            let admin = obj.data;//选中的行的数据
            edit(admin);
        }

    })

})

// 刷新
function reload() {
    //获取表单数据
    let formData = form.val("adm-search-form");
    // 将locked字符串转换成布尔值
    if(formData.locked === "是"){
        formData.locked = true;
    }else if(formData.locked === "否"){
        formData.locked = false;
    }else{
        formData.locked = null;
    }

    //重新加载表格，重新获取数据,where里是传给后台的数据
    table.reload('adm-tbl', {
        where: formData
    });
}

// 删除
function deleteByIds(ids) {
    const url = ctx + "/sys/api/v1/admin"
    $.ajax({
        url,
        method: "delete",
        data: {
            ids
        },
        traditional: true,
        success(resp) {//200
            if (resp.success) {
                layer.msg(resp.msg || "删除成功，共删除" + resp.data + "条数据")
            } else {
                layer.msg(resp.msg || "删除失败")
            }
        }, error(resp) {
            console.log(resp)
        }
    })
}

// 增加
function add() {
    layer.open({
        type: 2,//iframe层
        title: "新增管理员",
        area: ['680px', '520px'],
        skin: 'layui-layer-rim', // 加上边框
        content: "/vm/sys/admin/add",
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            let iframeWin = layero.find("iframe")[0].contentWindow;
            iframeWin.doSubmit(function (success) {
                if (success) {
                    layer.msg("添加成功");
                    layer.close(index);//关闭当前窗口
                    reload();
                } else {
                    layer.alert("添加失败", {
                        icon: 2,
                        title: "错误"
                    });
                }
            })
        }
    });
}

// 修改
function edit(admin) {
    layer.open({
        type: 2,//iframe层
        title: "修改管理员",
        area: ['680px', '520px'],
        skin: 'layui-layer-rim', // 加上边框
        content: "/vm/sys/admin/edit?id=" + admin.id,
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            let iframeWin = layero.find("iframe")[0].contentWindow;
            iframeWin.doSubmit(function (success) {
                if (success) {
                    layer.msg("修改成功");
                    layer.close(index);//关闭当前窗口
                    reload();
                } else {
                    layer.alert("修改失败", {
                        icon: 2,
                        title: "错误"
                    });
                }
            })
        }
    });
}
